package Utils;

import java.sql.*;

public class JdbcUtils {
    //可以把几个字符串定义成常量：用户名，密码，URL，驱动类
    private static final String USER = "root";
    private static final String PWD = "szyd@123!#";
    private static final String URL = "jdbc:mysql://24.59.13.202:3306/invx?useUnicode=true&characterEncoding=utf8&useSSL=false&useLegacyDatetimeCode=false&serverTimezone=Asia/Shanghai";

//    private static final String USER = "root";
//    private static final String PWD = "951120";
//    private static final String URL = "jdbc:mysql://localhost:3306/lq";

    private static final String DRIVER = "com.mysql.cj.jdbc.Driver";

    /**
     * 驱动的注册
     */
    static {
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 得到数据库的连接
     * @return : 返回数据库的连接
     * @throws SQLException : SQL的异常
     */
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(URL,USER,PWD);
    }

    /**
     * 关闭所有打开的资源
     * @param connection : 连接的对象
     * @param statement : 执行SQL语句的对象
     * @throws SQLException
     */
    public static void close(Connection connection, Statement statement) throws SQLException {
        try {
            assert statement != null;
            statement.close();
        }catch (SQLException e) {
            e.printStackTrace();
        }

        try {
            assert connection != null;
            connection.close();
        }catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void close(Connection connection, Statement statement, ResultSet resultSet) throws SQLException {
        try {
            assert statement != null;
            statement.close();
        }catch (SQLException e) {
            e.printStackTrace();
        }

        try {
            assert resultSet != null;
            resultSet.close();
        }catch (SQLException e) {
            e.printStackTrace();
        }

        try {
            assert connection != null;
            connection.close();
        }catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
